import utime as time
import usocket
import _thread  

def doConnect(host,port):
    global sock
    sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
    try :         
        sock.connect((host,port))
    except :
        pass
    return sock

def tcprecv(s):
    print('Running thread tcprecv...')
    while True:
        try:
            #接收信息并打印
            recvdata=s.recv(255)
        except OSError:
            print('TCP OSError')
        if len(recvdata)!=0:
            print(recvdata)
            # 例如接收到的数据格式 ：b'{"params": {"Relay":{"Relay_0":0,"Relay_1":0,"Relay_2":0,"Relay_3":0,"Relay_4":0,"Relay_5":0}}}'
            recvdata=recvdata.decode()
            recvdata=eval(recvdata)
            # {"params": {"Relay":{"Relay_0":0,"Relay_1":0,"Relay_2":0,"Relay_3":0,"Relay_4":0,"Relay_5":0}}}
    
        time.sleep(1)

def tcp_main(host,port):   
    global g_host ,g_port
    global sockLocal
    global sock
    g_host=host
    g_port=port
    print(host,port)   
    sockLocal = doConnect(host,port)
    _thread.start_new_thread(tcprecv, (sockLocal,))  

   
def update(value):
    global g_host,g_port
    global sockLocal
    try:
        msg=str(value)
        sockLocal.send(msg)
    except:
        print("\r\nsocket error,do reconnect ")
        time.sleep(3)
        sock.close()
        sockLocal = doConnect(g_host,g_port) 

